package org.dh2580.netty.demo.netty.protocol.privately;

import java.util.Map;

import com.alibaba.fastjson.JSON;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.util.CharsetUtil;

/**
 * @Author: hao.deng
 * @Date: 2019/5/8-下午4:04
 */
public class NettyMessageEncoder extends MessageToByteEncoder<NettyMessage> {

    @Override
    protected void encode(ChannelHandlerContext ctx, NettyMessage msg, ByteBuf out) throws Exception {

        out.writeInt(msg.getHeader().getCrcCode());
        out.writeInt(msg.getHeader().getLength());
        out.writeLong(msg.getHeader().getSessionId());
        out.writeByte(msg.getHeader().getType());
        out.writeByte(msg.getHeader().getPriority());
        out.writeInt(msg.getHeader().getAttachment().size());

        String key = null;
        byte[] keyArr = null;
        String value = null;

        for (Map.Entry<String, String> attachement : msg.getHeader().getAttachment().entrySet()) {
            key = attachement.getKey();
            keyArr = key.getBytes(CharsetUtil.UTF_8);

            out.writeInt(keyArr.length);
            out.writeBytes(keyArr);

            value = JSON.toJSONString(attachement.getValue());
            out.writeInt(value.length());
            out.writeBytes(value.getBytes(CharsetUtil.UTF_8));
        }


        if (msg.getBody() != null) {
            out.writeBoolean(true);

            byte[] bodyClass = msg.getBody().getClass().getName().getBytes(CharsetUtil.UTF_8);
            out.writeInt(bodyClass.length);
            out.writeBytes(bodyClass);

            byte[] body = JSON.toJSONString(msg.getBody()).getBytes(CharsetUtil.UTF_8);
            out.writeInt(body.length);
            out.writeBytes(body);
        } else {
            out.writeBoolean(false);
        }
    }

    public static void main(String[] args) {
        ByteBuf buf = Unpooled.buffer(128);
        buf.writeInt(1);
        buf.writeLong(2L);
        buf.writeBytes("hello".getBytes(CharsetUtil.UTF_8));

        System.out.println(buf.toString(CharsetUtil.UTF_8));
    }
}
